package com.max.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.max.common.LoginUserInfo;
import com.max.exceptions.BusinessException;
import com.max.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");

        if (StringUtils.isNotBlank(authorization) && SecurityContextHolder.getContext().getAuthentication() == null) {
            //解析jwt
            Jws<Claims> claimsJws = jwtUtils.parseJWTToken(authorization);
            if (!jwtUtils.verifyJWTToken(authorization, claimsJws.getBody().getSubject())) {
                throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), "用户未授权");
            }
            Claims body = claimsJws.getBody();
            LoginUserInfo userInfo = JSONObject.parseObject(JSON.toJSONString(body), LoginUserInfo.class);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userInfo, null, userInfo.getAuthorities());
            token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(token);
        }
        filterChain.doFilter(request, response);
    }
}
